package easy;

import util.PrintUtils;

public class Solution_1030 {

    public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
        boolean[][] flags = new boolean[rows][cols];
        int[][] res = new int[(rows) * (cols)][];
        int max = 0, index = 0;
        if (rCenter + cCenter > max) {
            max = rCenter + cCenter;
        }
        if (rows - rCenter - 1 + cols - cCenter - 1 > max) {
            max = rows - rCenter - 1 + cols - cCenter - 1;
        }
        if (rCenter + cols - cCenter - 1 > max) {
            max = rCenter + cols - cCenter - 1;
        }
        if (rows - rCenter - 1 + cCenter > max) {
            max = rows - rCenter - 1 + cCenter;
        }
        for (int i = 0; i <= max; i++) {
            int c_length = 0;

            // 左上角
            for (; c_length <= i && c_length <= cCenter; c_length++) {
                int r_length = i - c_length;
                if (r_length <= rCenter && !flags[rCenter - r_length][cCenter - c_length]) {
                    res[index++] = new int[]{rCenter - r_length, cCenter - c_length};
                    flags[rCenter - r_length][cCenter - c_length] = true;
                }
            }
            // 左下角
            c_length = 0;
            for (; c_length <= i && c_length <= cCenter; c_length++) {
                int r_length = i - c_length;
                if (rCenter + r_length < rows && !flags[rCenter + r_length][cCenter - c_length]) {
                    res[index++] = new int[]{rCenter + r_length, cCenter - c_length};
                    flags[rCenter + r_length][cCenter - c_length] = true;
                }
            }

            // 右上角
            c_length = 0;
            for (; c_length <= i && (c_length + cCenter) < cols; c_length++) {
                int r_length = i - c_length;
                if (r_length <= rCenter && !flags[rCenter - r_length][cCenter + c_length]) {
                    res[index++] = new int[]{rCenter - r_length, cCenter + c_length};
                    flags[rCenter - r_length][cCenter + c_length] = true;
                }
            }

            // 右下角
            c_length = 0;
            for (; c_length <= i && (c_length + cCenter) < cols; c_length++) {
                int r_length = i - c_length;
                if (rCenter + r_length < rows && !flags[rCenter + r_length][cCenter + c_length]) {
                    res[index++] = new int[]{rCenter + r_length, cCenter + c_length};
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution_1030 model = new Solution_1030();
//        int[][] ints = model.allCellsDistOrder(1, 2, 0, 0);
//        int[][] ints = model.allCellsDistOrder(2, 2, 0, 1);
        int[][] ints = model.allCellsDistOrder(2, 3, 1, 2);
        for (int[] arr : ints) {
            PrintUtils.arrayInt(arr);
        }
    }
}
